﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Net;

namespace FileManage
{
    class FileUpload
    {
        #region 变量
        private int userid;
        private string username;
        private int branchid;
        private string NASIP;
        private FTPClient ftp = null;//上传分店的FTP客户端
        private FTPClient ftpup = null;//上传至总店FTP客户端
        private string fileFullName;//文件上传的绝对路径 
        private string previewfullName;//上传缩略图的绝对路径
        private string strsuffix;//文件后缀名
        private string fileName;//文件名
        private string previewName;//缩略图文件名
        private string previewsuffix;//缩略图后缀名
        private string fileguid;
        private string title;
        private string projectremark;
        private string strGIud;
        private string attributeStr;
        private int flag;//判断该上传文件类型 0表示图片文件 1表示视频文件
        private bool ishead;//判断是否是总店在进行上传操作
        private string NASusername;//NAS用户名
        private string NASpassword;//NAS密码
        private string firstURL;
        private string ImageURL;//图片存储二级地址
        private string VideoURL;//视频存储二级地址
        private string HeadNASIP;//总店NAS服务器IP地址
        private string HeadnasUserName;//总店NAS用户名
        private string HeadnasPassword;//总店NAS密码

        #endregion

        #region 构造方法

        public FileUpload()
        {
            this.userid = 0;
            this.username = "";
            this.branchid = 0;
            this.NASIP = "";
            this.firstURL = "";
            this.ImageURL = "";
            this.VideoURL = "";
            this.NASusername = "";
            this.NASpassword = "";
            this.HeadNASIP = "";
            this.HeadnasUserName = "";
            this.HeadnasPassword = "";
        }

        /// <summary>
        /// 重载构造函数
        /// </summary>
        /// <param name="user_id">用户编号</param>
        /// <param name="user_name">用户名</param>
        /// <param name="file_FullName">文件上传的绝对路径</param>
        /// <param name="flag">上传文件的是图片（0），视频（1）</param>
        /// <param name="branch_id">用户所属分店编号</param>
        /// <param name="NAS_IP">用户所在分店NAS ip地址</param>
        /// <param name="is_head">是否是总店</param>
        /// <param name="first_URL">上传到NAS的一级路径</param>
        /// <param name="Image_URL">图片上传路径</param>
        /// <param name="Video_URL">视频上传路径</param>
        /// <param name="NASuser_name">NAS用户名</param>
        /// <param name="NASpassword">NAS密码</param>
        /// <param name="HeadNASIP">总店NAS ip 地址</param>
        /// <param name="HeadnasUserName">总店NAS用户名</param>
        /// <param name="HeadnasPassword">总店NAS密码</param>
        public FileUpload(int user_id, string user_name, string file_FullName, int flag, int branch_id, string NAS_IP, bool is_head, string first_URL, string Image_URL, string Video_URL, string NASuser_name, string NASpass_word, string Head_NASIP, string Headnas_UserName, string Headnas_Password)
        {
            this.userid = user_id;
            this.username = user_name;
            this.fileFullName = file_FullName;
            this.flag = flag;
            this.branchid = branch_id;
            this.NASIP = NAS_IP;
            this.ishead = is_head;
            this.firstURL = first_URL;
            this.ImageURL = Image_URL;
            this.VideoURL = Video_URL;
            this.NASusername = NASuser_name;
            this.NASpassword = NASpass_word;
            this.HeadNASIP = Head_NASIP;
            this.HeadnasUserName = Headnas_UserName;
            this.HeadnasPassword = Headnas_Password;
        }
        #endregion

        #region 文件验证操作
        private bool ValidateFile(string file_FullName, string preview_fullName)
        {
            this.fileFullName = file_FullName;
            this.previewfullName = preview_fullName;
            fileName = fileFullName.Substring(fileFullName.LastIndexOf(@"\") + 1);//文件名
            strsuffix = fileName.Substring(fileName.LastIndexOf(".") + 1).ToLower();//文件后缀名
            //判断可执行文件
            if (strsuffix == "exe" || strsuffix == "bat" || strsuffix == "sys" || strsuffix == "com")
            {
                //throw new IOException("不能上传可执行文件!");
                return false;
            }
            //判断是否选择文件
            if (string.IsNullOrEmpty(fileFullName))
            {
                //throw new IOException("请选择一个要上传的文件!");
                return false;
            }
            //上传视频时要同时上传预览图片
            if (flag == 1)
            {
                previewName = previewfullName.Substring(previewfullName.LastIndexOf(@"\") + 1);//预览图片文件名
                previewsuffix = previewName.Substring(previewName.LastIndexOf(".") + 1).ToLower();//预览图片文件后缀名
                //判断是否选择预览图片
                if (string.IsNullOrEmpty(previewfullName))
                {
                    //throw new IOException("请选择一个要上传的预览图片!");
                    return false;
                }
                //判断上传的是否为图片
                if (previewsuffix != "jpg" && previewsuffix != "bmp" && previewsuffix != "gif" && previewsuffix != "png")
                {
                    //throw new IOException("请上传图片文件!");
                    return false;
                }
                //判断上传的是否为视频
                if (strsuffix != "flv" && strsuffix != "wmv" && strsuffix != "mp4" && strsuffix != "avi" && strsuffix != "rmvb" && strsuffix != "f4v" && strsuffix != "mov")
                {
                    //throw new IOException("请上传视频文件!");
                    return false;
                }
            }
            //上传图片
            if (flag == 0)
            {
                if (strsuffix != "jpg" && strsuffix != "bmp" && strsuffix != "gif" && strsuffix != "png")
                {
                    //throw new IOException("请上传图片文件!");
                    return false;
                }
            }
            return true;
        }
        #endregion

        #region 上传文件
        private bool UpFile()
        {
            ftp = new FTPClient(NASIP, "", NASusername, NASpassword, 21);//分店FTP
            ftpup = new FTPClient(HeadNASIP, "", HeadnasUserName, HeadnasPassword, 21);//总店FTP
            string strArry = ",jpg,bmp,gif,png,flv,wmv,mp4,avi,rmvb,f4v,mov";
            int intjudge = strArry.IndexOf("," + strsuffix + ",");
            ftp.ChDir(firstURL);
            ftpup.ChDir(firstURL);
            if (flag == 1)
            {
                ftp.ChDir(VideoURL);
                ftpup.ChDir(VideoURL);
            }
            else if (flag == 0)
            {
                ftp.ChDir(ImageURL);
                ftpup.ChDir(ImageURL);
            }
            ftpup.Put(fileFullName, fileguid); //上传文件
            if (!ishead)
            {
                ftp.Put(fileFullName, fileguid);
            }

            if (intjudge >= 0)
            {
                if (!Thumbnail())
                {
                    try
                    {
                        string uri = "ftp://" + NASIP + firstURL + ImageURL + fileguid;
                        System.Net.FtpWebRequest reqFTP;
                        reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                        reqFTP.UseBinary = true;
                        if (ishead)
                        {
                            reqFTP.Credentials = new NetworkCredential(NASusername, NASpassword);
                        }
                        else
                        {
                            reqFTP.Credentials = new NetworkCredential(HeadnasUserName, HeadnasPassword);
                        }

                        reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
                        WebResponse response = reqFTP.GetResponse();
                        response.Close();
                        return true;
                    }
                    catch (Exception)
                    {
                        //MessageBox.Show("文件上传失败后删除文件失败！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }



        #endregion

        #region 生成缩略图方法
        public bool Thumbnail()
        {
            try
            {
                string pathImageFrom = "";
                if (flag == 1)
                {
                    pathImageFrom = previewfullName;
                }
                else if (flag == 0)
                {
                    pathImageFrom = fileFullName;
                }
                //生成缩略图
                if (GenThumbnail(pathImageFrom, 300, 170))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch
            {
                return false;
            }
        }
        #endregion

        #region 生成缩略图
        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="originalImagePath">源图路径（物理路径）</param>
        /// <param name="thumbnailPath">缩略图路径（物理路径）</param>
        /// <param name="width">缩略图宽度</param>
        /// <param name="height">缩略图高度</param>
        /// <param name="mode">生成缩略图的方式</param> 
        public bool GenThumbnail(string pathImageFrom, int width, int height)
        {
            Image imageFrom = null;
            try
            {
                imageFrom = Image.FromFile(pathImageFrom);
            }
            catch
            {
                //MessageBox.Show("图片格式无效或图片不存在！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                //uiContext.Post(UpdateUI, " ");
                return false;
            }
            if (imageFrom == null)
            {
                return false;
            }
            // 源图宽度及高度 
            int imageFromWidth = imageFrom.Width;
            int imageFromHeight = imageFrom.Height;
            // 生成的缩略图实际宽度及高度 
            int bitmapWidth = width;
            int bitmapHeight = height;
            // 生成的缩略图在上述"画布"上的位置 
            int X = 0;
            int Y = 0;
            // 根据源图及欲生成的缩略图尺寸,计算缩略图的实际尺寸及其在"画布"上的位置 
            if (bitmapHeight * imageFromWidth > bitmapWidth * imageFromHeight)
            {
                //bitmapHeight = imageFromHeight * width / imageFromWidth;
                Y = (height - bitmapHeight) / 2;
            }
            else
            {
                //bitmapWidth = imageFromWidth * height / imageFromHeight;
                X = (width - bitmapWidth) / 2;
            }
            // 创建画布 
            Bitmap bmp = new Bitmap(width, height);
            Graphics g = Graphics.FromImage(bmp);
            // 用白色清空    
            g.Clear(Color.White);
            // 指定高质量的双三次插值法。执行预筛选以确保高质量的收缩。此模式可产生质量最高的转换图像。 
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            //// 指定高质量、低速度呈现。 
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            // 在指定位置并且按指定大小绘制指定的 Image 的指定部分。 
            g.DrawImage(imageFrom, new Rectangle(X, Y, bitmapWidth, bitmapHeight), new Rectangle(0, 0, imageFromWidth, imageFromHeight), GraphicsUnit.Pixel);
            try
            {
                byte[] bsThumbnailImage = ImageToStream(bmp);
                //uiContext.Post(UpdateUI, "缩略图生成完成！");
                int USERID = userid;
                string USERNAME = username;
                int BRANCH_ID = branchid;
                string FILE_NAME = fileName;
                string URL = "";
                string PreFileName = "";
                if (previewfullName != null)
                {
                    PreFileName = previewfullName.Substring(previewfullName.LastIndexOf(@"\") + 1);
                }
                //byte[] bsPreviewImage = null;
                if (flag == 1)
                {
                    URL = firstURL + VideoURL;
                }
                else if (flag == 0)
                {
                    URL = firstURL + ImageURL;

                }
                //uiContext.Post(UpdateUI, "缩略图上传中！");
                UpImage.UpFileSoapClient server = new UpImage.UpFileSoapClient();
                string newVideoImage = strGIud + "." + previewsuffix;
                string[] ParaStr = new string[] { strGIud, FILE_NAME, title, projectremark, flag.ToString(), USERID.ToString(), USERNAME, BRANCH_ID.ToString(), URL, newVideoImage, PreFileName, attributeStr };
                if (server.UpFileRsout(ParaStr, bsThumbnailImage))
                {
                    server.InsertFile(strGIud, BRANCH_ID, ishead);
                    //uiContext.Post(UpdateUI, "缩略图上传成功！");
                    //uiContext.Post(UpdateUI, " ");
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                //uiContext.Post(UpdateUI, ex.Message.Substring(0, 4).ToString());
                return false;
            }
            finally
            {
                //显示释放资源 
                imageFrom.Dispose();
                bmp.Dispose();
                g.Dispose();
            }
        }

        public byte[] ImageToStream(Bitmap bmp)
        {
            System.IO.MemoryStream bstream = new System.IO.MemoryStream();
            bmp.Save(bstream, System.Drawing.Imaging.ImageFormat.Jpeg);
            bmp.Dispose();
            byte[] byteReturn = bstream.ToArray();
            bstream.Close();
            return byteReturn;
        }
        #endregion
    }
}
